
import ProTable from '@ant-design/pro-table';
import type { ProColumns } from '@ant-design/pro-table';
import { Modal } from 'antd';
import React, { useState } from 'react';
import {ProductType} from '../../model';
import request from '@/utils/request';
import { manufacturerOption,manufacturerOptionOnly } from '@/utils/utils';

export type FormValueType = {
    target?: string;
    template?: string;
    type?: string;
    time?: string;
    frequency?: string;
  } & Partial<ProductType>;

  
export type ChooseProps = {
    onCancel: (flag?: boolean, formVals?: FormValueType) => void;
    onSubmit: (values: ProductType[]) => Promise<void>;
    modalVisible: boolean;
    values: ProductType[];
    gift:number;
    self:boolean;
    admin:boolean;
    dealerId?:string;
  };

  
const ProductChooseForm: React.FC<ChooseProps> = (props)=>{
 
  // var index = props.values.findIndex((item)=>{
  //   return item.id === record.id&&item.is_gifts==props.gift;
  // });
    const map:any = {}
    props.values.forEach((item:any)=>{
      if(item.is_gifts==props.gift){
        map[item.id] = item.id
      }
    })


    async function queryProduct(params: any) {
      params.pageSize=1000;
      var data ;
      if(props.self){
        if(props.dealerId){
          params.dealerId = props.dealerId
        }
        if(props.gift===1&&!props.admin){
          data =  request('/xwyl/dealerGift/getGiftList4Dealer', {
            params,
          })
        }else{
          data =  request('/xwyl/product/dealerProductData', {
            params,
          })
        }
      }else{
        data =  request('/xwyl/product/productData', {
          params,
        });
      }
      return data;
    }
    
    const [selectedRowsState, setSelectedRows] = useState<any[]>();

    const rowSelection = {
      onChange: (key:any, selectedRows:any) => {
        setSelectedRows(selectedRows);
      },
      getCheckboxProps: (record:any) => {
        return {
          disabled: map[record.id],
          name: record.name,
        }
      }
    };
    
    const columns: ProColumns<ProductType>[] = [
      {
        title: '厂家',
        dataIndex: 'manufacturer',
        valueType:'select',
        hideInSearch:true,
        valueEnum:manufacturerOption(),
        width:80
      },
      {
        title: '厂家',
        dataIndex: 'manufacturer',
        valueType:'select',
        hideInTable:true, 
        valueEnum:manufacturerOptionOnly(),
        width:80
      },
        {
          title:'产品名称',
          dataIndex: 'product_name',
          render:(_,record:any)=>{
            if(map[record.id]){
              return <span>{record.product_name}<span style={{color:'#f10000'}}>（您已选择）</span></span>
            }else{
              return record.product_name
            }
          }
        },
        {
          title:"产品型号",
          dataIndex: 'product_standard',
        },
        {
          title: '单位',
          dataIndex: 'packing_unit',
          hideInSearch:true,
        },
      ];
    
    return (
      <Modal
        title="选择产品"
        width={1000}
        destroyOnClose={true}
        visible={props.modalVisible}
        onOk={()=>{
            var data = selectedRowsState?.filter((item:any)=>{
              item.is_gifts = props.gift;
              if(props.gift==0){
                item.numbs=item.minimum;
              }else{
                item.numbs=0;
              }
              return !item.choose;
            });
            // console.log(data)
            props.onSubmit(data);
            setSelectedRows([]);
        }}
        onCancel={()=>{
            props.onCancel();
        }}
      >
        <div hidden={!props.self} style={{fontSize:12,color:'#f10000'}}>
        【付款注意事项】<br/>
1、产品已升级为合并下单，并支付到银行账户中 <br/>
【发货时间问题】<br/>当日14：00之前付款的，当天有货的产品会发出，超过14：00付款的次日有货的产品发出
        </div>
        <ProTable<ProductType>
          headerTitle='产品列表'
          scroll={{ y: 300 }}
          toolBarRender={false}
          request={async(params, sorter, filter) =>
              queryProduct({ ...params, sorter, filter }).then(res=>{
                if(!props.admin){
                  // var nameMap:any = uniqueNameArray(props.values,'product_name');
                  // if(props.gift==1){
                  //   //赠品模式下，首先把当前有的类型过滤下，然后把触发赠品的去掉
                  //   var data=res.data.filter((item:ProductType)=>{
                  //     return nameMap.indexOf(item.product_name)>=0
                  //   })
                  //   res.data=data;
                  // }
                }
                return res;
              })
          }
          columns={columns}
          rowKey="id"
          pagination={false}
          search={{
            filterType: 'query',
            layout: 'horizontal',
        }}
            rowSelection={{
              type: "checkbox",
              ...rowSelection,
            }}
          />
      </Modal>
    );
}
export default ProductChooseForm;